<template>
<div id="uesrList">
    <!--搜索和添加新用户-->
    <el-row>
        <el-col :span="6">
             <el-input placeholder="请输入内容" v-model="text" class="input-with-select" ref="iptVal">
                 <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
             </el-input>
        </el-col>
        <el-col :span="6">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
         </el-col>
    </el-row>
   
    <!--添加用户的弹出框-->
    <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> 
            <el-form-item label="用户名" prop="name">
                <el-input v-model="ruleForm.name" ref="userName"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass" hide-required-asterisk="true" >
                <el-input type="password" v-model="ruleForm.pass" autocomplete="off" ref="password"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
                <el-input v-model="ruleForm.email" ref="email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phone" >
            <el-input type="phone" v-model.number="ruleForm.phone" autocomplete="off" ref="phone"></el-input>
        </el-form-item>
    </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible=false">取 消</el-button>
            <el-button type="primary" @click="addUser(ruleForm)">确 定</el-button>
        </span>
    </el-dialog>
    <!--用户列表-->
    <el-table :data="userData" border style="width: 100%">
        <el-table-column  label="#" width="50">
            <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column  label="状态" width="180" >
            <template slot-scope="scope">                   
                <el-switch v-model="scope.row.mg_state" 
                    active-color="#13ce66" 
                    inactive-color="#ff4949" 
                    @change="onOff(scope.row)"
                ></el-switch>
            </template>
        </el-table-column>
        <el-table-column  label="操作" width="200">
            <template slot-scope="scope">
            <!--编辑用户信息-->
            <el-button type="primary" icon="el-icon-edit" size="mini" 
            @click="editUser(scope.row.username,scope.row.id,scope.row.mobile,scope.row.email)"></el-button>
            <el-dialog
                title="编辑用户信息"
                :visible.sync="edit"
                width="50%"
                :before-close="handleClose"
                :append-to-body="true"
             >
            <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="name">
                    <el-input  ref="editname" disabled="" :value="editForm.name" ></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="editForm.email" ref="editEmail" ></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone" >
                    <el-input type="phone" v-model.number="editForm.phone" autocomplete="off" ref="editPhone" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="edit = false">取 消</el-button>
                <el-button type="primary" @click="editSubmit(editForm)">确 定</el-button>
            </span>
            </el-dialog>
            <!--删除用户信息-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
            <!--设置用户角色-->
            <el-button type="warning" icon="el-icon-setting" size="mini"
             @click="set(scope.row.username,scope.row.role_name,scope.row.id)"></el-button>
            <el-dialog
                title="设置用户角色"
                :visible.sync="dialogSet"
                width="30%"
                :before-close="handleClose"
                class="setuser"
            >
            <p>当前的用户 {{setForm.name}}</p>
            <p>当前的角色 {{setForm.role_name}}</p>
            <div>分配新角色 
                <el-select v-model="value" placeholder="请选择" @change="select">
                    <el-option
                        v-for="item in setForm.roles"
                        :id="item.id"
                        :key="item.value"
                        :label="item.roleName"
                        :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogSet = false">取 消</el-button>
                <el-button type="primary" @click="setUserOk">确 定</el-button>
            </span>
            </el-dialog>
            </template>
        </el-table-column>

     </el-table>
<!--分页-->
    <div class="page">
        <el-pagination
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="currentPage4"
            :page-sizes="[10, 5, 2, 15]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userList.total">
        </el-pagination>
    </div>

</div>
</template>

<script>
export default {
    data(){
        //添加新用户的表单验证
        let validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } 
            else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }   
         };
          let checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('手机号不能为空'));
                } 
                else {
                    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                    
                    if (reg.test(value)) {
                        callback();
                    } 
                    else {
                        return callback(new Error('请输入正确的手机号'));
                    }
                }
        };
        return {
            text:"",
            dialogVisible: false,
            dialogSet: false,
            value:"",
            ruleForm: {
                name: '',
                pass: '',
                email: '',
                phone:""
            },
            editForm: {
                name: '',
                pass: '',
                email: '',
                phone:"",
                id:0
            },
            setForm: {
                name:"",
                role_name:"",
                role_id:-1,
                id:-1,
                roles:[] //所有角色的集合
            },
            searchUser:{
                id:-1,
                name:"",
                searchData:[]
            },
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                ],
                pass: [
                    { validator: validatePass, trigger: 'blur' ,required: true}
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                email:[
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                phone:[
                    { required: true, validator: checkPhone, trigger: 'blur' },
                    
                ]
            },
            userList:[], //总数据
            userData:[], // 获取到的用户数据列表
            pagenum:1,  // 默认是第一页
            pagesize:10,// 每页显示10条
            currentPage4: 1,
            totalpage:0,
            edit:false,
            finRole:"",//设置的角色名
            rolesData:[] //角色列表
        }
    },
 
    methods:{
         handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        },
           //获取用户列表的数据
        getuserData(){
            let token =localStorage.getItem("token")
            this.$http.get('users',{
                params:{pagenum:this.pagenum,pagesize:this.pagesize},
                headers: {'Authorization': token}}
                ).then(result=>{
                if(result.body.meta.status == 200){
                    this.userData = result.body.data.users;
                    this.userList = result.body.data
                    //总页数等于总数据的条数除以每页的条数
                    this.totalpage = Math.ceil(this.userList.total/this.padeszie) 
                   //console.log(this.userData)
                }
                else{
                    console.log("获取数据失败")
                }
           })
        },
         //获取角色列表数据
         getRolesData(){
               this.$http.get("roles",{headers: {'Authorization': localStorage.getItem("token")}}).then(res=>{
               this.setForm.roles = res.body.data;
               this.rolesData = res.body.data
               //给每一项添加一个value值 渲染列表需要
                this.setForm.roles.forEach((item,i)=>{
                      item.value=item.id
                })
               //console.log(this.setForm.roles)
             })
         },
        //当前页变动时候触发的事件
        handleCurrentChange(val){
            //val是当前的页码值
            this.pagenum = val ; 
            this.getuserData()
         },
         handleSizeChange(val){
             //val 是每页多少条
             this.pagesize = val
             this.getuserData()
         },
         //添加新用户
         addUser(){
            let token =localStorage.getItem("token")
            let username = this.$refs.userName.value;
            let email = this.$refs.email.value || "";
            let phone = this.$refs.phone.value || "" 
            let password = this.$refs.password.value   
             this.$refs.ruleForm.validate((valid) => {
          if (valid) {
                this.dialogVisible = false
            this.$http.post("users",{username:username,password:password,email:email,mobile:phone},
                 {headers: {'Authorization': token}}).then(res=>{
                if(res.body.meta.status == 201){
                        this.$message({
                        type: 'success',
                        message: '添加成功!'
                        });
                    let data=res.body.data;
                    this.getuserData()
                }
                else{
                    console.log("获取数据失败")
                }
            })
          } 
          else {
            return false;
          }
        });
        },
         //修改用户信息的弹窗
         editUser(name,id,mobile,email){
           this.edit = true;
           //获取到了点击这一行的用户名 赋值给修改页面的用户名
           this.editForm.name = name
           this.editForm.id = id;
           this.editForm.email = email || ""
           this.editForm.phone = mobile || ""
         },
         //提交修改的用户信息
         editSubmit(editForm){
             let token = localStorage.getItem("token")
             this.$refs.editForm.validate((valid) => {
                if (valid) {
                   this.edit = false
                    this.$http.put("users/"+this.editForm.id,
                        { email:this.editForm.email,mobile:this.editForm.phone },
                        {headers:{"Authorization":token}}).then(res=> {
                    if(res.body.meta.status == 200){
                            this.$message({
                                message: '更新成功',
                                type: 'success'
                            });
                    //刷新前台页面的数据
                    this.userData.some(item=>{
                      if(item.id == res.body.data.id){
                         item.mobile = res.body.data.mobile
                         item.email = res.body.data.email;
                         return true
                        }
                    })
                }
                        else{
                            this.$message.error('修改失败');
                        }
                    })
                } 
                    else {
                        return false;
                    }
                });
            },
         //删除用户
         delUser(id){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //提交删除的数据给后台
                this.$http.delete("users/"+id,{headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
                    //删除对应前端的数据
                    this.userData.some((item,i)=>{
                    if(item.id == id){
                        this.userData.splice(i,1)
                        return true
                    }
                })
                  //使总条数减一
                 this.userList.total--
                })
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
            });          
        });

            
        },
        //设置用户角色
        set(user,role,id){
            this.dialogSet = true
            this.setForm.role_name = role;
            this.setForm.name = user;
            this.setForm.id = id
        },
        //当下拉选项框中的值发生改变的时候 val为当前选项框中的value值
        select(val){
            this.setForm.role_id = val
        },
        //确定提交设置用户的角色
        setUserOk(){
            this.dialogSet = false
            this.$http.put("users/"+this.setForm.id+"/role",
            {rid:this.setForm.role_id},
            {headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
                if(res.body.meta.status == 200){
                    this.setForm.role_id = res.body.data.rid
                //先根据返回的role_id在角色数据里面找到对应的角色名字
                //再根据返回的id值找到userData中对应的那一项 将角色名赋给他
                    this.rolesData.some(item=>{
                        if(item.id == this.setForm.role_id){
                        this.finRole = item.roleName
                        return true
                        }
                    })
                    this.userData.some(item=>{
                        if(item.id== this.setForm.id ){
                            item.role_name = this.finRole
                            return true
                        }
                    })
                    this.$message({
                    message: '设置角色成功',
                    type: 'success'
                    });
                }
                else{
                     this.$message.error('设置角色失败');
                }
            })
        },
        //根据用户名查询用户
        search(){
            this.searchUser.name = this.$refs.iptVal.value //获取输入的内容
            if(this.searchUser.name == ""){
                this.getuserData()  //如果没有输入查找的用户名 则渲染所有用户信息
                return
            }
            this.$http.get("users",
                {
                    params:{ pagenum:this.pagenum,pagesize:this.pagesize,query:this.searchUser.name },
                    headers:{ "Authorization":localStorage.getItem("token") }
                },
                ).then(res=>{
                if(res.body.meta.status == 200){
                  this.userData = res.body.data.users
                 }
            })
        },
        //切换用户状态
        onOff(row){
            this.$http.put("users/"+row.id+"/state/"+row.mg_state,{},
            {headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
                if(res.body.meta.status == 200){
                    this.$message({
                    message: '设置状态成功',
                    type: 'success'
                    });
                }
                else{
                    row.mg_state = !row.mg_state
                     this.$message.error('设置状态失败');
                }
            })
        }       
    },
   
      created() {
          this.$store.commit("changeTitle",{"t1":"用户管理","t2":"用户列表"})
           this.getuserData(),
           this.getRolesData()
        }
    }

</script>

<style lang="scss">
    #uesrList{
        .el-button{
            margin: 0 !important
        }
      .el-col{
          margin-right: 10px
      }
       .el-dialog{
           width:50% !important;
           .el-input,.el-input__inner{
               width:100% !important;
           }
       }
       .el-table{
           margin-top:20px;
           margin-bottom: 20px
       }
       .page{
           .el-input__inner,.el-input{
               width:100px;
           }
        
         }
         .setuser{
             .el-dialog__body{
                 padding: 0 20px;
             p{
                 margin-bottom: 40px
             }
            }
         }
     }  
    .el-select-dropdown{
        min-width: 100px !important;
     } 

</style>